package com.csrcb.services;

import com.csrcb.entity.User;
import com.csrcb.tools.Response;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname UserService
 * @Date 2021年7月30日10:05:40
 * @Created by gangye
 */
@Service
@Slf4j
public class UserService {

    @Autowired
    private RestTemplate okHttpTemplate;

    public User getOneUser(User user){
        log.info("请求的user信息{}",user);
        log.info("debug断点调试使用日志");
        Integer id = user.getId();
        user.setId(id);
        user.setName("demoB张三");
        user.setAddress("苏州");
        log.info("返回的user信息{}",user);
        return user;
    }

    public List<User> getUserList(){
        List<User> users = new ArrayList<>();
        User user1 = new User(1,"张三","苏州");
        User user2 = new User(2,"李四","上海");
        User user3 = new User(3,"王五","北京");
        users.add(user1);
        users.add(user2);
        users.add(user3);
        return users;
    }

    //通过resttemplate调用springboot_demoA获取信息，查看日志
    public User getDemoAUserInfo(User user) throws IOException {
        String urlDemoA = "http://127.0.0.1:8001/api/springbootDemoA/user/getOneUser";
        log.info("请求体信息{}",user);
        HttpHeaders headers = new HttpHeaders();
        ObjectMapper jsonMapper = new ObjectMapper();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String userJsonString = jsonMapper.writeValueAsString(user);
        HttpEntity<String> httpEntity = new HttpEntity<>(userJsonString, headers);
        log.info("使用restTemplate调用springboot_demoA应用的请求信息:{}",httpEntity);
        ResponseEntity<String> responseEntity = okHttpTemplate.postForEntity(urlDemoA, httpEntity, String.class);
        log.info("使用restTemplate调用springboot_demoA返回报文:{}",responseEntity);
        String restRespenseStr = responseEntity.getBody();
        Response demoAResponse = jsonMapper.readValue(restRespenseStr, Response.class);
        User demoAUser = null;
        if (demoAResponse.isOK() && null != demoAResponse.get("data")){
            demoAUser = jsonMapper.readValue(jsonMapper.writeValueAsString(demoAResponse.get("data")), User.class);
        }
        return demoAUser;
    }
}
